import path from "node:path";
import { fileIsExits, getDirname } from "./util.js";
import fs from "node:fs";
import fse from "fs-extra";
import sharp from "sharp";

// 1 获取参数
const args = process.argv.slice(2);
const dirName = args.join(" ");
const dirPath = path.join(process.cwd(), dirName || "/");

// 2 检查路径是否为文件夹
const stats = fileIsExits(dirPath);
if (!stats || !stats.isDirectory()) {
  console.log("路径不是一个文件夹");
  process.exit(1);
}

// 3 读取文件夹中的所有文件
const imageExtensions = [
  ".jpg",
  ".jpeg",
  ".png",
  ".gif",
  ".webp",
  ".bmp",
  ".tiff",
];
const imageFiles: string[] = [];

// 递归遍历文件夹
function traverseDirectory(directory: string) {
  const files = fs.readdirSync(directory);

  for (const file of files) {
    const fullPath = path.join(directory, file);
    const stat = fs.statSync(fullPath);

    if (stat.isDirectory()) {
      traverseDirectory(fullPath);
    } else if (stat.isFile()) {
      const ext = path.extname(file).toLowerCase();
      if (imageExtensions.includes(ext)) {
        imageFiles.push(fullPath);
      }
    }
  }
}
traverseDirectory(dirPath);

// 4 压缩图片
// async function compressImages() {
//   console.log(`找到 ${imageFiles.length} 个图片文件，开始压缩...`);
//   let totalOriginalSize = 0;
//   let totalNewSize = 0;

//   for (const file of imageFiles) {
//     const ext = path.extname(file).toLowerCase();
//     const fileStats = fs.statSync(file);
//     const originalSize = fileStats.size;
//     totalOriginalSize += originalSize;

//     // 根据文件类型选择合适的压缩参数
//     let compressedImage;

//     if (ext === ".png") {
//       compressedImage = await sharp(file)
//         .png({ quality: 50, compressionLevel: 9 })
//         .toBuffer();
//     } else if ([".jpg", ".jpeg"].includes(ext)) {
//       compressedImage = await sharp(file).jpeg({ quality: 50 }).toBuffer();
//     } else if (ext === ".webp") {
//       compressedImage = await sharp(file).webp({ quality: 50 }).toBuffer();
//     } else {
//       // 其他格式使用默认设置
//       compressedImage = await sharp(file).toBuffer();
//     }

//     fse.removeSync(file);
//   }
// }
// compressImages();
async function compressImages() {
  console.log(`找到 ${imageFiles.length} 个图片文件，开始压缩...`);

  let totalOriginalSize = 0;
  let totalNewSize = 0;

  for (const fileIndex in imageFiles) {
    try {
      const file = imageFiles[fileIndex];
      // 创建与原文件夹结构相同的临时文件夹
      const relativePath = path.relative(dirPath, file);
      const tmpDirPath = path.join(dirPath + "_tmp");
      const newFilePath = path.join(tmpDirPath, relativePath);

      // 确保目标文件夹存在
      const targetDir = path.dirname(newFilePath);
      fse.ensureDirSync(targetDir);

      const ext = path.extname(file).toLowerCase();
      const fileStats = fs.statSync(file);
      const originalSize = fileStats.size;
      totalOriginalSize += originalSize;

      // 根据文件类型选择合适的压缩参数
      let compressedImage;

      if (ext === ".png") {
        compressedImage = await sharp(file)
          .png({ quality: 60, compressionLevel: 9 })
          .toBuffer();
      } else if ([".jpg", ".jpeg"].includes(ext)) {
        compressedImage = await sharp(file).jpeg({ quality: 60 }).toBuffer();
      } else if (ext === ".webp") {
        compressedImage = await sharp(file).webp({ quality: 60 }).toBuffer();
      } else {
        // 其他格式使用默认设置
        compressedImage = await sharp(file).toBuffer();
      }

      // console.log(compressedImage);
      fs.writeFileSync(newFilePath, compressedImage, { flag: "w+" });

      // 计算压缩后的大小
      const newStats = fs.statSync(newFilePath);
      const newSize = newStats.size;
      totalNewSize += newSize;

      console.log(`压缩中：${+fileIndex + 1}/${imageFiles.length}`);
      // console.log(`压缩: ${file}`);
    } catch (error: any) {
      console.error(`处理 失败:`, error?.message);
    }
  }

  // 计算整体压缩比例
  const ratio =
    totalOriginalSize > 0
      ? Math.round((1 - totalNewSize / totalOriginalSize) * 100)
      : 0;

  // 格式化文件大小为MB/GB
  function formatSize(bytes: number): string {
    if (bytes < 1024) return bytes + " B";
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + " KB";
    if (bytes < 1024 * 1024 * 1024)
      return (bytes / (1024 * 1024)).toFixed(2) + " MB";
    return (bytes / (1024 * 1024 * 1024)).toFixed(2) + " GB";
  }

  const originalSizeFormatted = formatSize(totalOriginalSize);
  const newSizeFormatted = formatSize(totalNewSize);

  if (totalNewSize > 0) {
    console.log(
      `压缩完成！总体减小了 ${ratio}% (${originalSizeFormatted} -> ${newSizeFormatted})`
    );
  } else {
    console.log("没有压缩任何图片");
  }
}

// 运行压缩
compressImages();

function sleep(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
